package com.rickpan.service;

import com.rickpan.dto.response.SearchSuggestionResponse;
import com.rickpan.entity.FileInfo;
import com.rickpan.repository.FileInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 搜索服务
 *
 * @author RickPan Team
 * @since 2025-07-03
 */
@Service
public class SearchService {

    @Autowired
    private FileInfoRepository fileRepository;

    /**
     * 获取搜索建议
     * 根据用户输入的关键词搜索相关文件，返回搜索建议列表
     *
     * @param userId  用户ID
     * @param keyword 搜索关键词
     * @param limit   返回数量限制
     * @return 搜索建议列表
     */
    public List<SearchSuggestionResponse> getSearchSuggestions(Long userId, String keyword, Integer limit) {
        List<SearchSuggestionResponse> suggestions = new ArrayList<>();

        try {
            // 搜索文件建议
            List<SearchSuggestionResponse> fileSuggestions = getFileSuggestions(userId, keyword, limit);
            suggestions.addAll(fileSuggestions);

            // System.out.println("搜索建议结果: 关键词=" + keyword + ", 结果数量=" + suggestions.size());

        } catch (Exception e) {
            System.err.println("获取搜索建议失败: " + e.getMessage());
            e.printStackTrace();
        }

        return suggestions;
    }

    /**
     * 获取文件搜索建议
     * 根据文件名模糊匹配搜索用户的文件
     *
     * @param userId  用户ID
     * @param keyword 搜索关键词
     * @param limit   返回数量限制
     * @return 文件搜索建议列表
     */
    private List<SearchSuggestionResponse> getFileSuggestions(Long userId, String keyword, int limit) {
        List<SearchSuggestionResponse> suggestions = new ArrayList<>();

        try {
            Pageable pageable = PageRequest.of(0, limit);
            List<FileInfo> files = fileRepository.findByOwnerIdAndOriginalNameContainingIgnoreCaseAndIsDeletedFalseOrderByUpdatedAtDesc(
                    userId, keyword, pageable);

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            for (FileInfo file : files) {
                String fileIcon = getFileIcon(file.getMimeType());
                String fileSize = formatFileSize(file.getFileSize());
                String parentFolderName = getParentFolderName(file.getParentId());

                SearchSuggestionResponse suggestion = new SearchSuggestionResponse(
                        "file_" + file.getId(),
                        "file",
                        file.getOriginalName(),
                        file.getFilePath(),
                        fileIcon,
                        fileSize,
                        parentFolderName,
                        file.getParentId() != null ? file.getParentId().toString() : "0",
                        file.getUpdatedAt()
                );

                suggestions.add(suggestion);
            }

        } catch (Exception e) {
            System.err.println("获取文件建议失败: " + e.getMessage());
        }

        return suggestions;
    }



    /**
     * 根据文件MIME类型获取对应的图标标识
     *
     * @param mimeType 文件MIME类型
     * @return 图标标识字符串
     */
    private String getFileIcon(String mimeType) {
        if (mimeType == null) return "document";

        if (mimeType.startsWith("image/")) return "image";
        if (mimeType.contains("pdf")) return "pdf";
        if (mimeType.contains("word") || mimeType.contains("document")) return "word";
        if (mimeType.contains("excel") || mimeType.contains("spreadsheet")) return "excel";
        if (mimeType.contains("powerpoint") || mimeType.contains("presentation")) return "powerpoint";
        if (mimeType.startsWith("video/")) return "video";
        if (mimeType.startsWith("audio/")) return "audio";
        if (mimeType.contains("zip") || mimeType.contains("rar") || mimeType.contains("7z")) return "archive";

        return "document";
    }

    /**
     * 格式化文件大小为可读格式
     * 将字节数转换为B、KB、MB、GB等单位
     *
     * @param bytes 文件大小（字节）
     * @return 格式化后的文件大小字符串
     */
    private String formatFileSize(Long bytes) {
        if (bytes == null || bytes == 0) return "0 B";

        String[] units = {"B", "KB", "MB", "GB", "TB"};
        int unitIndex = 0;
        double size = bytes.doubleValue();

        while (size >= 1024 && unitIndex < units.length - 1) {
            size /= 1024;
            unitIndex++;
        }

        return String.format("%.1f %s", size, units[unitIndex]);
    }

    /**
     * 获取父文件夹名称
     * 根据父文件夹ID获取文件夹名称，用于搜索结果显示
     *
     * @param parentId 父文件夹ID
     * @return 父文件夹名称
     */
    private String getParentFolderName(Long parentId) {
        if (parentId == null || parentId == 0) {
            return "根目录";
        }
        return "文件夹";
    }
}
